package gosnoopers.fr;

import java.util.ArrayList;
import java.util.HashMap;

import lazy_listview.ImageLoader;
import lazy_listview.JSONfunctions;
import listview.CitiesAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;



 
 
public class Details extends Activity {
	public static String URL = "http://gosnoopers.com/victimes/app/detail?id=";
	public static String URLCONTENT = "http://gosnoopers.com/victimes/app/viewVictim/id/";
	
	ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String ID = "id";
    static String NAME = "name";
    static String ALIAS = "alias";
    public static JSONObject jsonobject;
    public static JSONArray jsonarray;
    public static JSONObject  jo;
    public static JSONArray aPhotos;
    ListView list;
    private Button btn_like_of_list_article_dashboard;
    private Button btn_comment_of_list_article_dashboard;
    private Dialog webViewDialog;  
    private WebView webView;  
    private Button btClose;  
    public int width = 0;
    
	CitiesAdapter adapter;
	final Context context = this;
	public static String strCityId = "";
	public static String victime_id = "";
	public static String email_author = "";
	//*******************check connect*************************
    public  boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
    //******************* Called when the activity is first created. */
       
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          this.requestWindowFeature(Window.FEATURE_NO_TITLE);
          setContentView(R.layout.detail);
          header();
          //**************get size of device********************
          DisplayMetrics metrics = context.getResources().getDisplayMetrics();
          width = metrics.widthPixels;
          //***************************************************
          Intent iin= getIntent();
          Bundle b = iin.getExtras();
          victime_id  = "";
          
          if(b!=null)
          {
        	  victime_id =(String) b.get("VICTIME_ID");
        	  new SessionManager(context).addVictimId(victime_id);              
          }
          Log.i("VICTIME_ID",victime_id);
          
          URL = "http://gosnoopers.com/victimes/app/detail?id="+victime_id;
          
          TextView text_view_landing_page_header = (TextView) findViewById(R.id.text_view_landing_page_header);
          text_view_landing_page_header.setText("Victime detail");
          
          URLCONTENT = "http://gosnoopers.com/victimes/app/viewVictim/id/"+victime_id;
          btn_like_of_list_article_dashboard = (Button) findViewById(R.id.btn_like_of_list_article_dashboard);
          btn_comment_of_list_article_dashboard = (Button) findViewById(R.id.btn_comment_of_list_article_dashboard);
          btn_comment_of_list_article_dashboard.setOnClickListener(new OnClickListener() {
       	   
        	  @Override  
              public void onClick(View v)  
              {  
        		  Intent goToNextActivity = new Intent(getApplicationContext(), Maps.class);
        		  
					goToNextActivity.putExtra("LAT", details_latitude);
					goToNextActivity.putExtra("LONG", details_longitude);
					
	               startActivity(goToNextActivity);
              }   
          });
          
          Button btn_send_message = (Button) findViewById(R.id.btn_send_message);
          btn_send_message.setOnClickListener(new OnClickListener() {
          	   
        	  @Override  
              public void onClick(View v)  
              {  
        		  Intent goToNextActivity = new Intent(getApplicationContext(), ContactActivity.class);
					//goToNextActivity.putExtra("ID_COUNTRY", id_country.getText());
        		  goToNextActivity.putExtra("VICTIME_ID", victime_id);
        		  goToNextActivity.putExtra("EMAIL", email_author);
					
	               startActivity(goToNextActivity);
              }   
          });
	       // add button listener
          btn_like_of_list_article_dashboard.setOnClickListener(new OnClickListener() {
	   
        	  @Override  
              public void onClick(View v)  
              {  
                  //Display the WebView dialog  
                  webViewDialog.show();  
              }   
          });
        	//Create a new dialog  
              webViewDialog = new Dialog(this);  
              //Remove the dialog's title  
              webViewDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);  
              //Inflate the contents of this dialog with the Views defined at 'webviewdialog.xml'  
              webViewDialog.setContentView(R.layout.victime_detail);  
              //With this line, the dialog can be dismissed by pressing the back key  
              webViewDialog.setCancelable(true);  
        
              //Initialize the Button object with the data from the 'webviewdialog.xml' file  
              btClose = (Button) webViewDialog.findViewById(R.id.bt_close);  
              //Define what should happen when the close button is pressed.  
              btClose.setOnClickListener(new OnClickListener()  
              {  
                  @Override  
                  public void onClick(View v)  
                  {  
                      //Dismiss the dialog  
                      webViewDialog.dismiss();  
                  }  
              });  
        
              //Initialize the WebView object with data from the 'webviewdialog.xml' file  
              webView = (WebView) webViewDialog.findViewById(R.id.wb_webview);  
              //Scroll bars should not be hidden  
              webView.setScrollbarFadingEnabled(false);  
              //Disable the horizontal scroll bar  
              webView.setHorizontalScrollBarEnabled(false);  
              //Enable JavaScript  
              webView.getSettings().setJavaScriptEnabled(true);  
              //Set the user agent  
              webView.getSettings().setUserAgentString("AndroidWebView");  
              //Clear the cache  
              webView.clearCache(true);  
              //Make the webview load the specified URL  
              webView.loadUrl(URLCONTENT); 
        	  

              
    	      if(!isNetworkAvailable()){
    	    	  CharSequence text = "Please turn of wifi or 3G";
    	    	  Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
    	    	  toast.show();
    	      }else{
    	    	  new DownloadJSON().execute();
    	      }
    	      
    	      
    	      
    	      ImageView btn_setting = (ImageView) findViewById(R.id.image_setting);
    			btn_setting.setOnClickListener(new OnClickListener() {

    				@Override
    				public void onClick(View v) {
    					Intent goToNextActivity = new Intent(getApplicationContext(), Settings.class);
    					goToNextActivity.putExtra("VICTIME_ID", victime_id);
    					goToNextActivity.putExtra("EMAIL", email_author);
    					
    		            startActivity(goToNextActivity);
    				}
    			});
	  	  
      }
      
      /*
       * ****************************  header **********************************
       */
      public void header() {
  		ImageView btn_setting = (ImageView) findViewById(R.id.image_setting);
  		btn_setting.setOnClickListener(new OnClickListener() {

  			@Override
  			public void onClick(View v) {
  				Intent goToNextActivity = new Intent(getApplicationContext(),
  						Settings.class);
  				startActivity(goToNextActivity);
  			}
  		});

  		/**
  		 * Kiem user da dang nhap hay chua 1. hein thi icon user 2. hien thi
  		 * icon add victimes
  		 */
  		ImageView image_open_left_navigation = (ImageView) findViewById(R.id.image_open_left_navigation);
  		ImageView icon_header_form = (ImageView) findViewById(R.id.icon_header_form);
  		if (MainActivity.userId.equalsIgnoreCase("0")) {
  			image_open_left_navigation.setVisibility(View.VISIBLE);
  			icon_header_form.setVisibility(View.GONE);
  		} else {
  			image_open_left_navigation.setVisibility(View.GONE);
  			icon_header_form.setVisibility(View.VISIBLE);
  		}

  		image_open_left_navigation.setOnClickListener(new OnClickListener() {

  			@Override
  			public void onClick(View v) {
  				Intent goToNextActivity = new Intent(getApplicationContext(),
  						MainActivity.class);
  				startActivity(goToNextActivity);
  			}
  		});

  		icon_header_form.setOnClickListener(new OnClickListener() {

  			@Override
  			public void onClick(View v) {
  				Intent goToNextActivity = new Intent(getApplicationContext(),
  						FormFirst.class);
  				startActivity(goToNextActivity);
  			}
  		});
  	}
      
    //********************************************************************  
      public static double details_latitude = 0;
      public static double details_longitude = 0;
      public static JSONObject details_maps;
      
   //*********************** DownloadJSON AsyncTask***********************
      private class DownloadJSON extends AsyncTask<Void, Void, Void> {
   
          @Override
          protected void onPreExecute() {
              super.onPreExecute();

          }
   
          @Override
          protected Void doInBackground(Void... params) {
              // Create an array
              arraylist = new ArrayList<HashMap<String, String>>();
              // Retrieve JSON Objects from the given URL address
              String _url = URL+"&w="+width;
              jsonobject = JSONfunctions.getJSONfromURL(_url);

              try {
                  // Locate the array name in JSON
                  //jsonarray = jsonobject.getJSONArray("data");
            	  jo = jsonobject.getJSONObject("data");
            	  
            	  aPhotos = jo.getJSONArray("photos");
            	  
                  String strError = jsonobject.getString("error");
                  String message = jsonobject.getString("message");
                  
                  String name = jo.getString("name");
                  
                  
                  if(strError == "false"){

                	   
                      
                  }else{
                  	Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
        	    	  	toast.show();
                  }
                  
              } catch (JSONException e) {
                  Log.e("Error", e.getMessage());
                  e.printStackTrace();
              }
              return null;
          }
   
          @Override
          protected void onPostExecute(Void args) {
        	  
        	  TextView title = (TextView) findViewById(R.id.title);
        	  TextView des = (TextView) findViewById(R.id.des);
        	  TextView about = (TextView) findViewById(R.id.about);
        	  try {
				title.setText(jo.getString("name"));
				des.setText(jo.getString("inscrition"));
	        	about.setText(jo.getString("local_victim"));
	        	email_author = jo.getString("email");
	        	
	        	
	        	details_maps = jo.getJSONObject("maps");
          	  details_latitude = details_maps.getDouble("latitude");
          	  details_longitude = details_maps.getDouble("longtitude");
          	  System.out.println("FFFFFFFFFFFFFFFFFFFF "+details_latitude);
          	  System.out.println("FFFFFFFFFFFFFFFFFFFF "+details_longitude);
	        	
	        	
	              ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
	              ImagePagerAdapter adapter = new ImagePagerAdapter();
	              adapter.mImages = new String[aPhotos.length()];
	              for (int i = 0; i < aPhotos.length(); i++) {
	            	  
	            	  adapter.mImages[i] = aPhotos.get(i).toString();
	            	  
	            	  
	              }
	              
	              viewPager.setAdapter(adapter);
        	  } catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
        	  }
        	  
        	  
        	  
        	  
              
          }
      }
      
      //****************************************************************
      private class ImagePagerAdapter extends PagerAdapter {

    	    /*private String[] mImages={
    	            "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS9Al5gEU32LxgOsBvOcaGJGYbU9ib2Tl83QQqwkSxOhWAIHBdfgQ"
    	    };*/
    	  	private String[] mImages= new String[100];
    	    @Override
    	    public int getCount() {
    	      return mImages.length;
    	    }

    	    @Override
    	    public boolean isViewFromObject(View view, Object object) {
    	      return view == ((ImageView) object);
    	    }

    	    @Override
    	    public Object instantiateItem(ViewGroup container, int position) {
    	      Context context = Details.this;
    	      //ImageView imageView = new ImageView(context);
    	      
    	      
    	   // Imageview to show
    	      ImageView imageView = new ImageView(context);
    	      // ImageLoader class instance
    	      ImageLoader imgLoader = new ImageLoader(getApplicationContext());
    	       // Loader image - will be shown before loading image
    	      imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    	      /*imageView.setMaxHeight(10000);
    	      imageView.setAdjustViewBounds(true);*/
    	      
    	      
    	      //android:fadingEdge="none"
    	      // whenever you want to load an image from url
    	      // call DisplayImage function
    	      // url - image url to load
    	      // loader - loader image, will be displayed before getting image
    	      // image - ImageView 
    	      imgLoader.DisplayImage(mImages[position],  imageView );
    	      ((ViewPager) container).addView(imageView, 0);
    	      return imageView;
    	      
    	    }

    	    @Override
    	    public void destroyItem(ViewGroup container, int position, Object object) {
    	      ((ViewPager) container).removeView((ImageView) object);
    	    }
      }
      
  }